package az.mecid.rssreader.tasks;

import az.mecid.rssreader.model.entity.FeedEntity;
import az.mecid.rssreader.model.entity.FeedItemEntity;
import az.mecid.rssreader.model.utils.EMF;
import com.google.appengine.api.datastore.Link;
import com.google.appengine.api.datastore.Text;
import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.fetcher.FeedFetcher;
import com.sun.syndication.fetcher.FetcherException;
import com.sun.syndication.fetcher.impl.FeedFetcherCache;
import com.sun.syndication.fetcher.impl.HashMapFeedInfoCache;
import com.sun.syndication.fetcher.impl.HttpURLFeedFetcher;
import com.sun.syndication.io.FeedException;

import javax.persistence.EntityManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;
import java.util.List;
import java.util.logging.Logger;

/**
 * Created by IntelliJ IDEA.
 * User: mega
 * Date: 21.03.2010
 * Time: 14:01:45
 */
@SuppressWarnings("unchecked")
public class FeedUpdateTaskServlet extends HttpServlet{

    private Logger logger = Logger.getLogger(FeedUpdateTaskServlet.class.getName());

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException{
        Long id = Long.parseLong(req.getParameter("id"));

        EntityManager em = EMF.get().createEntityManager();

        FeedEntity feed = em.find(FeedEntity.class,id);

        long last_loaded = feed.getLast_load();
        try {
            URL url = new URL(feed.getUrl());
//old version ...dct

//            SyndFeedInput input = new SyndFeedInput();
//            SyndFeed syndFeed = input.build(new InputStreamReader(url.openStream(),"UTF-8"));
//new version ...
            FeedFetcherCache cache = HashMapFeedInfoCache.getInstance();
            FeedFetcher fetcher = new HttpURLFeedFetcher(cache);
            SyndFeed syndFeed = fetcher.retrieveFeed(url);
//end ...
            List<SyndEntry> items = syndFeed.getEntries();

            feed.setLast_load(System.currentTimeMillis());
            em.merge(feed);

            for (SyndEntry item : items) {
                if (item.getPublishedDate().after(new Date(last_loaded))) {
                    Text text = new Text(item.getDescription().getValue());
                    Link link = new Link(item.getLink());
                    long time = item.getPublishedDate().getTime();
                    String title = item.getTitle();

                    em.persist(new FeedItemEntity(feed.getId(), title, text, time, link, null));
                }
            }
        } catch (MalformedURLException e) {
            logger.info(e.getMessage());
        } catch (IOException e) {
            logger.info(e.getMessage());
        } catch (FeedException e) {
            e.printStackTrace();
        } catch (FetcherException e) {
            e.printStackTrace();
        } finally {
            em.close();
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
